package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.mapper.AlbumAttributeValueMapper;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.AlbumStatMapper;
import com.atguigu.tingshu.album.service.AlbumAttributeValueService;
import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.AlbumStat;
import com.atguigu.tingshu.vo.album.AlbumInfoVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class AlbumInfoServiceImpl extends ServiceImpl<AlbumInfoMapper, AlbumInfo> implements AlbumInfoService {

	@Autowired
	private AlbumInfoMapper albumInfoMapper;

	@Autowired
	private AlbumAttributeValueMapper albumAttributeValueMapper;

	@Autowired
	private AlbumStatMapper albumStatMapper;

	@Autowired
	private AlbumAttributeValueService attributeValueService;

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Autowired
	private RedisTemplate redisTemplate;

	//@Autowired
	//private RedissonClient redissonClient;

	@Override
	public void saveAlbumInfo(AlbumInfoVo albumInfoVo) {
		//保存专辑表
		Long albumId = saveAlbum(albumInfoVo);
		//保存专辑标签值表
		this.attributeValueService.saveAlbumAttributeValue(albumInfoVo, albumId);
		//初始化专辑状态表
		initAlbumStat(albumId,SystemConstant.ALBUM_STAT_PLAY);
		initAlbumStat(albumId, SystemConstant.ALBUM_STAT_SUBSCRIBE);
		initAlbumStat(albumId, SystemConstant.ALBUM_STAT_BROWSE);
		initAlbumStat(albumId, SystemConstant.ALBUM_STAT_COMMENT);

	}

	private Long saveAlbum(AlbumInfoVo albumInfovo) {
		//保存专辑表
		AlbumInfo albumInfo = new AlbumInfo();
		//2.1属性拷贝
		BeanUtils.copyProperties(albumInfovo,albumInfo);
		//设置主播id
		Long userId = AuthContextHolder.getUserId();//从THreadLocal中获取用户id
		albumInfo.setUserId(userId==null ? 1: userId);
		//设置免费试听声音数
		albumInfo.setTracksForFree(5);
		//审核状态
		albumInfo.setStatus(SystemConstant.ALBUM_STATUS_PASS);
		this.save(albumInfo);
		Long albumInfoId = albumInfo.getId();
		return albumInfoId;
	}
	private void initAlbumStat(Long albumId, String statType) {
		AlbumStat albumStat = new AlbumStat();
		albumStat.setAlbumId(albumId);
		albumStat.setStatType(statType);
		this.albumStatMapper.insert(albumStat);
	}
}
